<?php

namespace Liuhelong\LaravelAdmin\Wechat\Models;

use Encore\Admin\Traits\DefaultDatetimeFormat;
use Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Storage;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class WechatOffiaccountUser extends Model
{
    use DefaultDatetimeFormat;
	protected $primaryKey = 'openid';
	public $incrementing = false;
	private $wechat;
	private $next_openid = null;
	private $openids = [];
	protected $dates = [
		'subscribe_time'
	];
	
	public function __construct(){
		parent::__construct();
		$this->wechat = app('Liuhelong_wechat_service');
	}
	
	
	public function paginate()
    {
		// 将微信openid数组存到本地cache方便后期调用
		$openids = Cache::remember('openids',3600, function() {
			$this->getOpenids();
			return $this->openids;
		});
		
        $perPage = Request::get('per_page', 20);
        $page = Request::get('page', 1);
		
        $start = ($page-1)*$perPage;
		
        $data = $this->wechat->handle('user','select',[array_slice($openids,$start,$perPage)]);
		
		$list = static::hydrate($data['user_info_list']);
        $paginator = new LengthAwarePaginator($list, count($openids), $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }

    public static function with($relations)
    {
        return new static;
    }
	
	protected function findOrFail($id)
	{
		$data = $this->wechat->handle('user','get',[$id]);
		return static::newFromBuilder($data);
		
	}
	private function getOpenids(){
		
		$list = $this->wechat->handle('user','list',[$this->next_openid]);
		extract($list);
		
		if($count){
			
			$this->openids = array_merge($this->openids,$data['openid']);
			$this->next_openid = $next_openid;
			$this->getOpenids();
		}
	}
}
